package cn.com.callback

import cn.com.elite.EliteBean
import cn.com.elite.Util
import cn.com.kh.KHDBConfig
import cn.com.kh.KHUtil
import com.alibaba.fastjson.JSONObject
import org.apache.commons.logging.Log
import org.apache.commons.logging.LogFactory

import javax.servlet.http.HttpServletRequest
import javax.servlet.http.HttpServletResponse

/**
 *
 * @Title: apiSyncDemo* @Description:系统API接口开发Demo ，重点关注业务逻辑部分
 * @author: LiJuntao* @date 2021-07-13 23:58:55
 *
 */

public class apiWXCode implements ServiceBackInvoke {
    private static final Log log = LogFactory.getLog(apiWXCode.class);

    public String doCallBack(EliteBean eliteBean, HttpServletRequest request, HttpServletResponse response) {
        String DOMAIN = KHDBConfig.getParam(eliteBean, "NGSDOM");

        response.setCharacterEncoding("UTF-8");

        String getMethod = request.getMethod();
        log.debug("getMethod:" + getMethod);
        String dataSourceID = "dataSource";

        //获取所有参数名
        Enumeration e = request.getParameterNames();
        while (e.hasMoreElements()) {
            //获取当前参数名
            String parameterName = (String) e.nextElement();
            //再通过request.getParameter("")的方法来获取对应参数名的值
            log.debug(parameterName + ": " + request.getParameter(parameterName));
        }

        String code = request.getParameter("code");
        String state = request.getParameter("state");
        String opsource = request.getParameter("opsource");
        String opdynid = request.getParameter("opdynid");
        String expand = request.getParameter("expand");

        opdynid = KHUtil.isNull(opdynid) ? "DHBII3" : opdynid;

        log.debug("回调参数信息【code】：" + code + "【state】：" + state + "【opsource】：" + opsource + "【opdynid】：" + opdynid + "【expand】：" + expand);

        // 调用微信获取OPENID
        String APPID = null;
        String APPSECRET = null;
        if (opsource == "wxc") {
            APPID = KHDBConfig.getParam(eliteBean, "WX1-ID");
            APPSECRET = KHDBConfig.getParam(eliteBean, "WX1-KE");

        } else if (opsource == "wxs") {
            APPID = KHDBConfig.getParam(eliteBean, "WX2-ID");
            APPSECRET = KHDBConfig.getParam(eliteBean, "WX2-KE");

        } else {

            log.warn("未知类型公众号嵌入警告:" + opsource);
            return opsource;
        }
        log.debug("获取到的微信公众号配置信息【APPID】：" + APPID + "【APPSECRET】：" + APPSECRET);

        // 通过Code信息获取openid
        if (!KHUtil.isNull(APPID)) {
            JSONObject apiTokenJson = JSONObject.parseObject(Util.doHttpGet("https://api.weixin.qq.com/sns/oauth2/access_token?appid=" + APPID + "&secret=" + APPSECRET + "&code=" + code + "&grant_type=authorization_code", "UTF-8", 5000, 0));

            String access_token = apiTokenJson.getString("access_token");
            int expires_in = apiTokenJson.getInteger("expires_in");
            String refresh_token = apiTokenJson.getString("refresh_token");
            String openid = apiTokenJson.getString("openid");
            String scope = apiTokenJson.getString("scope");
            log.debug("获取到的微信用户信息【access_token】：" + access_token + "【expires_in】：" + expires_in + "【refresh_token】：" + refresh_token + "【openid】：" + openid);

            // 检查当前OPENID对应的账号类型
            List selectExits = null;
            if (opsource == "wxc") {
                selectExits = eliteBean.chaxun_sql("select customer_guid as userid, loginname, 'customer' as usertype, 2 as sno from customer where open_id = '" + openid + "' order by sno limit 1", dataSourceID);

            } else if (opsource == "wxs") {
                selectExits = eliteBean.chaxun_sql("select staff_id as userid, loginname , 'staff' as usertype, 1 as sno from staff where openid = '" + openid + "' order by sno limit 1", dataSourceID);

            } else {
                log.warn("未知类型公众号嵌入获取用户信息警告:" + opsource);
                return opsource;
            }

            // 获取当前登录人在系统中的信息
            String userid = "";
            String usertype = "";
            if (selectExits.size() > 0) {
                Map selectExitsm = selectExits.get(0);
                userid = selectExitsm.get("userid");
                usertype = selectExitsm.get("usertype");

            } else {
                userid = openid;
                usertype = "notype";
            }
            log.debug("获取当前登录人在系统中的信息:" + userid + "/" + usertype);

            // 获取NGS页面信息短码
            String NGSShortenLinkURL = DOMAIN + "/ngsapitask/api/apiShortenLink?dynid=" + opdynid + "&userid=" + userid + "&usertype=" + usertype + "&woid=&taskid=&expand=" + expand + "&cbtype=&opsource=" + opsource;
            log.debug("获取NGS页面短码URL：" + NGSShortenLinkURL);

            JSONObject apiLinkJson = JSONObject.parseObject(Util.doHttpGet(NGSShortenLinkURL, "UTF-8", 5000, 0));
            log.debug("获取NGS页面信息短码：" + apiLinkJson.toString());

            // 解析NGS短码调用返回
            String linkURL = apiLinkJson.getString("message");

            response.sendRedirect(linkURL);

        } else {
            log.warn("获取到异常的公众号APPID警告:" + APPID);
            return opsource;
        }
    }
}